#!/bin/bash
./wait-for-it.sh webapp:8000 --

function upload_location() {
  response=$(curl -c cookies.txt -b cookies.txt http://webapp:8000/locations_files_download)
  csrftoken=$(grep -oP 'input type="hidden" name="csrfmiddlewaretoken" value="\K[^"]+' <<< "$response")
  curl -X POST -F "file=@uszips.csv" -H "Referer: http://webapp:8000/locations_files_download" -H "X-CSRFToken: $csrftoken" -H "Content-Type: multipart/form-data" webapp:8000/locations_files_download --cookie "csrftoken=$csrftoken"
#  response=$(curl -c cookies.txt -b cookies.txt http://127.0.0.1:8000/locations_files_download)
#  csrftoken=$(grep -oP 'input type="hidden" name="csrfmiddlewaretoken" value="\K[^"]+' <<< "$response")
#  curl -X POST -F "file=@uszips.csv" -H "Referer: http://127.0.0.1:8000/locations_files_download" -H "X-CSRFToken: $csrftoken" -H "Content-Type: multipart/form-data" 127.0.0.1:8000/locations_files_download --cookie "csrftoken=$csrftoken"
}

function upload_car() {
  for ((i=1;i<2;i++))
  do
  number=$(( 1 + $RANDOM % 999 ))
#  curl -X POST -F "payload_type=$number" http://127.0.0.1:8000/api/v1/cars
  curl -X POST -F "payload_type=$number" http://webapp:8000/api/v1/cars
  done
}

#caller=5
for (( i = 5; i > 0; i-- ));
do
  echo webapp
#  if exec 3>/dev/tcp/127.0.0.1/8000
  if exec 3>/dev/tcp/webapp/8000
  then
    upload_location
    upload_car
    break
  fi
    echo "Could not connect to server. Время `date +%H:%M`. Еще $i попытка(и)"
    sleep 20
done

while true; do
#  curl http://127.0.0.1:8000/reupdate
  curl http://webapp:8000/reupdate
  sleep 3m
done
